package yto.freemarker.springcloud.controller;


import com.google.common.collect.Lists;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import yto.freemarker.springcloud.entity.User;
import yto.freemarker.springcloud.repository.UserRepository;

import java.util.Collections;
import java.util.List;

/**
 * @author dongxing
 * @create 2017-12-24 16:25
 **/
@RestController
@AllArgsConstructor(onConstructor_ = {@Autowired})
public class UserController {

    private final UserRepository userRepository;

    private final EurekaClient eurekaClient;

    private final DiscoveryClient discoveryClient;

    @GetMapping("/simple/{id}")
    public User findById(@PathVariable Long id) {
        return this.userRepository.findById(id).orElse(User.builder().build());

    }

    /**
     * 服务的信息，比如url
     *
     * @return
     */
    @GetMapping("/eureka-instance")
    public String serviceUrl() {
        InstanceInfo instanceInfo = this.eurekaClient.getNextServerFromEureka("SERVICE-PROVIDER-MOVIE", false);
        return instanceInfo.getHomePageUrl();
    }


    /**
     *
     * 服务的信息
     *
     * @return
     */
    @GetMapping("/instance-info")
    public List<ServiceInstance> showInfo() {
        List<ServiceInstance> instances = this.discoveryClient.getInstances("SERVICE-PROVIDER-MOVIE");
        return instances;
    }


    @PostMapping("/test")
    public User postUser(@RequestBody User user) {
        return user;
    }

    // 该请求不会成功
    @GetMapping("/get-test")
    public User getUser(@PathVariable("username") String username, @PathVariable("age") Short age) {
        User user = User.builder().username(username).age(age).build();
        return user;
    }

    @GetMapping("/list-all")
    public List<User> getUsers() {
        List<User> list = Lists.newArrayList();
        Collections.addAll(list, User.builder().id(1L).name("张三").build(), User.builder().id(2L).name("李四").build());
        return list;
    }


    @RequestMapping(value = "/eureka/apps/{serviceName}", method = RequestMethod.GET)
    public String findServiceInfoFromEurekaByServiceName(@PathVariable("serviceName") String serviceName) {
        return serviceName;
    }
}
